package com.jrx.anytxn.param.utils;

import com.jrx.anytxn.param.entity.PrOrganizationTable;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.List;

/**
 * @Title: TargzUtil.java
 * @Description: gzip文件压缩和解压缩工具类
 * @author zcc
 * @date 2020-12-09
 * @version V1.0
 */
public class TargzUtil {
    private static final Logger logger = LoggerFactory.getLogger(TargzUtil.class);

    /**
     *
     * @Title: pack
     * @Description: 将一组文件打成tar包
     * @param sources 要打包的原文件数组
     * @param target 打包后的文件
     * @return File    返回打包后的文件
     * @throws
     */
    public static File pack(List<File> sources, File target, String tarpath, String today, PrOrganizationTable org){
        //创建目录
        String filePath = tarpath + org.getTenantId() + File.separator + today + File.separator;
        File file1 = new File(filePath);
        if (!file1.exists()) {
            file1.mkdirs();
        }

        try(FileOutputStream out = new FileOutputStream(target);
             TarArchiveOutputStream os = new TarArchiveOutputStream(out)){
            for (File file : sources) {
                os.putArchiveEntry(new TarArchiveEntry(file, file.getName()));
                IOUtils.copy(new FileInputStream(file), os);
                os.closeArchiveEntry();
            }
        }catch (IOException e) {
            logger.error("压缩文件异常，异常信息：",e);
            throw new RuntimeException("压缩文件异常");
        }

        return target;
    }

    /**
     *
     * @Title: pack
     * @Description: 将一组文件打成tar包
     * @param sources 要打包的原文件数组
     * @param target 打包后的文件
     * @return File    返回打包后的文件
     * @throws
     */
    public static File pack(List<File> sources, File target){
        try(FileOutputStream out = new FileOutputStream(target);
            TarArchiveOutputStream os = new TarArchiveOutputStream(out)){
            for (File file : sources) {
                os.putArchiveEntry(new TarArchiveEntry(file, file.getName()));
                IOUtils.copy(new FileInputStream(file), os);
                os.closeArchiveEntry();
            }
        }catch (IOException e) {
            logger.error("压缩文件异常，异常信息：",e);
            throw new RuntimeException("压缩文件异常");
        }
        return target;
    }
}